import { loginAPI, getUserInfoAPI, getBaseUserInfoAPI } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken() || '',
  UserInfo: ''
}
const getters = {}
const mutations = {
  setToken(state, newToken) {
    setToken(newToken)
    state.token = newToken
  },
  setUserInfoAPI(state, newUserInfo) {
    state.UserInfo = newUserInfo
  },
  // 清除token和用户信息以及cookie里的token
  logout(state) {
    state.token = ''
    removeToken()
    state.UserInfo = ''
  }

}
const actions = {
  login(store, loginForm) {
    return new Promise((resolve, reject) => {
      loginAPI(loginForm).then(res => {
        const token = res.data
        store.commit('setToken', token)
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  async getUserInfo(store) {
    const res = await getUserInfoAPI()
    const res2 = await getBaseUserInfoAPI(res.data.userId)
    res2.data.staffPhoto = 'www.qqq15346png' // 设置一个假的图片地址来检测默认图片的效果
    const res3 = { ...res.data, ...res2.data }
    store.commit('setUserInfoAPI', res3)
    return res3 // return的目的是为了八天之后做权限管理用
  } }

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
